const fileInput = document.getElementById('excelFile');
const processBtn = document.getElementById('processBtn');
const subjectIdInput = document.getElementById('subjectId');
const passwordInput = document.getElementById('password'); // 添加这一行
const resultDiv = document.getElementById('result');

// 检查文件、科目ID和密码是否都已填写
function checkReady() {
  processBtn.disabled = !fileInput.files.length || !subjectIdInput.value.trim() || !passwordInput.value.trim(); // 修改这一行
}

fileInput.addEventListener('change', checkReady);
subjectIdInput.addEventListener('input', checkReady);
passwordInput.addEventListener('input', checkReady); // 添加这一行
checkReady(); // 初始化

processBtn.addEventListener('click', async () => {
  const file = fileInput.files[0];
  const sid = parseInt(subjectIdInput.value.trim(), 10);
  const password = passwordInput.value.trim(); // 添加这一行

  if (isNaN(sid) || sid <= 0) {
    alert('请填写有效的科目ID（正整数）');
    return;
  }

  const reader = new FileReader();

  reader.onload = async (e) => {
    const arrayBuffer = e.target.result;
    const uint8Array = new Uint8Array(arrayBuffer);

    resultDiv.innerHTML = '<p>🔄 正在处理文件...</p>';

    // 👇 把password也传过去
    const result = await window.electronAPI.processExcel(uint8Array, file.name, sid, password); // 修改这一行

    if (result.success) {
      resultDiv.innerHTML = `
        <button id="downloadBtn" style="padding:10px 20px;font-size:16px;">
          💾 下载处理后的文件
        </button>
      `;

      document.getElementById('downloadBtn').addEventListener('click', async () => {
        const downloadResult = await window.electronAPI.downloadFile(
          result.buffer,
          result.defaultSaveName
        );
        if (!downloadResult.canceled) {
          alert(`文件已保存到：\n${downloadResult.filePath}`);
        }
      });
    } else {
      resultDiv.innerHTML = `<p style="color:red">❌ ${result.message}</p>`;
    }
  };

  reader.readAsArrayBuffer(file);
});